layui.config({
    base: basePath+'/layui/lay/modules/'
}).use(['form','element','tabrightmenu'], function() {
    var form = layui.form;
    layer = layui.layer;
    element = layui.element;
    var $ = layui.$
    var rightmenu_ = layui.tabrightmenu;
    navTree.init(("#nav"),basePath +"/loginAuth/getUserFuncJSONList");

    indexUtil.createSysCollection();

    rightmenu_.render({
        container: '#index-table-container',
        filter: 'xbs_tab',
    });

    $('.container .left_open i').click(function(event) {
        if($('.left-nav').css('left')=='0px'){
            $('.left-nav').animate({left: '-221px'}, 100);
            $('.page-content').animate({left: '0px'}, 100);
            $('.page-content-bg').hide();
        }else{
            $('.left-nav').animate({left: '0px'}, 100);
            $('.page-content').animate({left: '221px'}, 100);
            if($(window).width()<768){
                $('.page-content-bg').show();
            }
        }
    });

    $('.page-content-bg').click(function(event) {
        $('.left-nav').animate({left: '-221px'}, 100);
        $('.page-content').animate({left: '0px'}, 100);
        $(this).hide();
    });

    $('.layui-tab-close').click(function(event) {
        $('.layui-tab-title li').eq(0).find('i').remove();
    });

    $("#index-reLogin").click(function(event){

        layer.open({
            type: 1,
            area: [350+'px', 250 +'px'],
            fix: false, //不固定
            maxmin: true,
            shadeClose: true,
            shade:0.4,
            title: "<i class='layui-icon layui-icon-note'></i> "+"登录",
            content: $("#index-reLogin-dom").html(),
            success:function(){
                $("input[name=userNo]").val(localStorage.getItem("userNo")||'')
            }
        });
        event.stopPropagation()
    })


    $("a[index-theme='index-theme']").click(function(e){
        indexUtil.setTheme($(this).attr("class"))
    })

    form.on("submit(login-form-bt)",function(data){

        $.getJSON(basePath+"/loginAuth/login",data.field,function(item){
            //console.log(JSON.stringify(item))
            if(item.code == 0){
                //alert(item.data.url)
                //localStorage.setItem("token",item.data.token)
                localStorage.setItem("userName",item.data.userName)
                localStorage.setItem("userNo",item.data.userNo)
                localStorage.setItem("userGrade",item.data.userGrade)
                $.cookie("token",item.data.token,{path:"/"+webContext} )
                layer.msg("登录成功..",function(){
                    location.reload()
                })
            }else{
                layer.msg(item.message)
            }
        });
        return false;
    })
    //<a href="#">前台首页</a>
    $(".to-index>a").html(localStorage.getItem("indexLinkName")).click(function(){
        window.open(localStorage.getItem("indexLink"))
     })


    //主题
    indexUtil.setTheme();
    //公告
    indexUtil.setNotice();

    navTree.adaptScreen(".adapt-screen")

    if(sysLogo !=null && sysLogo != "" && sysLogo != "null"){
        $(".logo").empty().append("<a href='#'><img src='"+ basePath+"/static/images/"+sysLogo+"' style='width:200px;height:45px;float:left' ></a>")
    }else{
        $(".logo").empty().append("<a href='#'>"+sysName+"</a>")
    }

});



//触发事件
var tab = {
    tabAdd: function(title,url,id){
        //新增一个Tab项
        element.tabAdd('xbs_tab', {
            title: title
            ,content: '<iframe tab-id="'+id+'"  frameborder="0" class="x-iframe layadmin-iframe" src="'+url+'"  ></iframe>'
            ,id: id
        })
    }
    ,tabDelete: function(othis){
        //删除指定Tab项
        element.tabDelete('xbs_tab', '44'); //删除：“商品管理”


        othis.addClass('layui-btn-disabled');
    }
    ,tabChange: function(id){
        //切换到指定Tab项
        element.tabChange('xbs_tab', id); //切换到：用户管理
    }
    ,fresh:function(){
        element.render("tab",'xbs_tab');
    }
};


/*弹出层*/
/*
 参数解释：
 title   标题
 url     请求的url
 id      需要操作的数据id
 w       弹出层宽度（缺省调默认值）
 h       弹出层高度（缺省调默认值）
 */
function x_admin_show(title,url,w,h){
    if (title == null || title == '') {
        title=false;
    };
    if (url == null || url == '') {
        url="404.html";
    };
    if (w == null || w == '') {
        w=($(window).width()*0.9);
    };
    if (h == null || h == '') {
        h=($(window).height() - 50);
    };
    layer.open({
        type: 2,
        area: [w , h ],
        fix: false, //不固定
        maxmin: true,
        shadeClose: true,
        shade:0.4,
        title: "<i class='layui-icon layui-icon-note'></i> "+title,
        content: url+"?userCode="+userNo
    });
}

/*关闭弹出框口*/
function x_admin_close(){
    var index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
}


var navTree = {
    init:function(treeId,url){
        //console.log(url)
        $.ajax(url,{
            dataType:"json",
            type:"get",
            //data:{token:localStorage.getItem("token")},
            success:function(rdata){
                //console.log(JSON.stringify(rdata))
                if(rdata.code == 0){
                    navTree.createDomNode($(treeId),rdata.data);
                    //console.log($(treeId).html())
                }else{
                    layer.msg(rdata.message)
                }

                navTree.createAction()
            }
        });
    },

    createAction:function(){
        //左侧菜单效果
        // $('#content').bind("click",function(event){

        $('.left-nav #nav .adapt-screen').mousemove(function(event){
            $(this).addClass("xd-bg-color")
            $(this).find("i,cite").css("font-size",15)
        })

        $('.left-nav #nav .adapt-screen').mouseout(function(event){
            $(this).removeClass("xd-bg-color")
            $(this).find("i,cite").css("font-size",12)
        })

        $('.left-nav #nav li').click(function (event) {

            if($(this).children('.sub-menu').length){
                if($(this).hasClass('open')){
                    $(this).removeClass('open');
                    $(this).find('.nav_right').html('&#xe697;');
                    $(this).children('.sub-menu').stop().slideUp();
                    $(this).siblings().children('.sub-menu').slideUp();
                }else{
                    $(this).addClass('open');
                    $(this).children('a').find('.nav_right').html('&#xe6a6;');
                    $(this).children('.sub-menu').stop().slideDown();
                    $(this).siblings().children('.sub-menu').stop().slideUp();
                    $(this).siblings().find('.nav_right').html('&#xe697;');
                    $(this).siblings().removeClass('open');
                }
            }else{

                var url = $(this).children('a').attr('_href');
                var title = $(this).find('cite').html();
                var index  = $('.left-nav #nav li').index($(this));


                navTree.createAction2(title,url,event)

                //for (var i = 0; i <$('.x-iframe').length; i++) {
                //    var id =  $('.x-iframe').eq(i).attr('tab-id')
                //    console.log($('.x-iframe').eq(i).attr('src') ,id)
                //    if($('.x-iframe').eq(i).attr('tab-id')==index+1){
                //        tab.tabChange(index+1);
                //        event.stopPropagation();
                //        return;
                //    }
                //};
                //
                //tab.tabAdd(title,url,index+1);
                //tab.tabChange(index+1);
            }

            event.stopPropagation();

        })

    },

    createDomNode:function(treeDom,jsonArray) {
        $.each(jsonArray,function(index,data){
            var node1 = $("<li></li>");
            if(data.children == null || data.children.length <= 0){
                node1.append('<a _href="'+basePath+'/'+data.path+"?funcId="+data.id+'&rptId='+data.rptId+'"><i class="layui-icon '+data.icon+'"></i><cite>'+data.funcName+'</cite></a>')
                node1.addClass("adapt-screen")
                node1.click(function(){
                    var width = $(document.body).width()
                    if(width < 768){
                        $('.left-nav').animate({left: '-221px'}, 100);
                        $('.page-content').animate({left: '0px'}, 100);
                        $('.page-content-bg').hide();
                    }
                });
            }else{
                node1.append('<a><i class="layui-icon '+data.icon+' "></i><cite>'+data.funcName+'</cite><i class="iconfont nav_right">&#xe697;</i></a>');
                var node2 = $('<ul class="sub-menu"></ul>');
                navTree.createDomNode(node2,data.children);
                node1.append(node2)
            }
            treeDom.append(node1)
        });
    },
    //添加适配小屏幕，点击菜单：左侧菜单自动影藏
    adaptScreen:function(dom){

    },
    /*
    * 点击其他链接，创建tab
    * */
    createAction2:function(title,url,event){
        var flag =  false
        var length = $('.x-iframe').length;
        var index =  length
        for (var i = 0; i <  length ; i++) {
            if($('.x-iframe').eq(i).attr('src') == url ){
                index  =  $('.x-iframe').eq(i).attr('tab-id')
                flag = true
                break;
            }
        };
        if(!flag ){
            var id = (new Date()).getTime()
            tab.tabAdd(title,url,id);
            tab.tabChange(id);
        }else{
            tab.tabChange(index );
        }
        event.stopPropagation();
        return ;
    },
}


var indexUtil = {
    //收藏夹
    createSysCollection:function(){
        $("#index-collection").empty()
        var url = basePath+"/collection/query"
        $.ajax(url,{
            dataType:"json",
            type:"get",
            //data:{token:localStorage.getItem("token")},
            success:function(rdata){
                //console.log(JSON.stringify(rdata))
                if(rdata.code == 0){
                    if(rdata.data){
                        $.each(rdata.data,function(index,functions){
                            //<dd><a onclick="navTree.createAction2('${function.funcName}',basePath+'/${function.path}?funcId=${function.id}',event)"><i class="layui-icon ${function.icon}"></i>${function.funcName}&nbsp;&nbsp;&nbsp;&nbsp;<i class="layui-icon layui-icon-close delCollection" _col-id="${it.id}" style="font-size: 12px; color: red;"></i></a></dd>
                            var ddhtml = "<dd>" +
                                "<a onclick=navTree.createAction2('"+functions.funcName+"','"+basePath+"/"+functions.path+"?funcId="+functions.funcId+"&rptId="+functions.rptId+"',event)  >" +
                                "<i class='layui-icon "+ functions.icon+"'></i>" +  functions.funcName + "&nbsp;&nbsp;&nbsp;&nbsp;" +
                                "<i class='layui-icon layui-icon-close delCollection' _col-id='"+functions.collectId+"' style='font-size: 12px; color: red;' ></i>" +
                                "</a>"+
                                "</dd>"
                            $("#index-collection").append(ddhtml)
                         })
                        $(".delCollection").click(function(event){
                           var id = $(this).attr("_col-id")
                            $.getJSON(basePath+"/collection/del",{id:id,token:token},function(rst){
                                if(rst.code == 0){
                                    indexUtil.createSysCollection()
                                }else{
                                    layer.msg(rst.msg)
                                }
                            })
                            event.stopPropagation()
                        })
                    }else{
                        $("#index-collection").append("<dd><a>暂无...</a></dd>")
                    }
                }
            }
        });
    },

    setTheme:function(theme){
        var dom = $("div[index-theme='index-theme-set']")
        var leftNav = $(".left-nav")
        var xdTheme =  localStorage.getItem("xdTheme")
        if(theme){
            if(xdTheme){
                dom.removeClass(xdTheme).addClass(theme)
                leftNav.removeClass(xdTheme).addClass(theme)
            }else{
                dom.addClass(theme)
                leftNav.addClass(theme)
            }
            localStorage.setItem("xdTheme",theme)
        }else {
            if(xdTheme){
                dom.removeClass(xdTheme).addClass(xdTheme)
                leftNav.removeClass(xdTheme).addClass(xdTheme)
            }else{
                theme = "layui-bg-black"
                dom.addClass(theme)
                leftNav.addClass(theme)
                localStorage.setItem("xdTheme",theme)
            }
        }
    },
    setNotice:function(){
        var url = basePath +"/sysNotice/indexNoticeCount"
        var noticeDom = $("#index-notice")
        $.ajax(url,{
            dataType:"json",
            type:"post",
            //data:{token:localStorage.getItem("token")},
            success:function(rdata){
                //console.log(JSON.stringify(rdata))
                noticeDom.find("a").click(function(event){
                    navTree.createAction2(rdata.data.funcName,basePath +"/"+rdata.data.path+"?funcId="+rdata.data.id+"&rptId="+rdata.data.rptId,event)
                    noticeDom.find(".layui-badge").remove()
                })
                noticeDom.find(".layui-badge").html(rdata.count)
            }
        });
    }
}

